import React, { useState, useRef, useMemo, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { CustomDialog } from '@/components/CustomDialog'
import FileUploadButton from '@/components/FileUploadButton'
import { type UploadResponse } from '@/services'
import { Pencil, Plus, Trash2, X } from 'lucide-react'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { toast } from '@/hooks/use-toast'
import { commonService } from '@/services'
import { useFileStore, type FileItem } from '@/stores/fileStore'

interface Tag {
  id: string
  name: string
  isDefault: boolean
  isEditing?: boolean
}

interface UploadCardProps {
  children?: React.ReactNode
  onSuccess?: () => void
  open: boolean
  onOpen: (state: boolean) => void
  editItem?: FileItem | null
}

const UploadDialog = ({
  children,
  onSuccess,
  open,
  onOpen,
  editItem,
}: UploadCardProps) => {
  const uploadCallback = useRef<null | (() => Promise<UploadResponse>)>(null)
  // const [open, setOpen] = useState(false)
  const { tagList } = useFileStore()
  const [tags, setTags] = useState<Tag[]>([])
  const [newTagName, setNewTagName] = useState('')
  const [isPublic, setIsPublic] = useState('0')
  const [fileName, setFileName] = useState('') // 添加文件名状态
  const [selectedTags, setSelectedTags] = useState<string[]>([]) // 添加选中标签状态

  useEffect(() => {
    if (editItem && open) {
      console.log('editItem:', editItem)
      setFileName(editItem.name)
      setIsPublic(editItem.public ? '1' : '0')
      setSelectedTags(editItem.tags || [])
    }
  }, [editItem, open])

  const showTagList: Tag[] = useMemo(() => {
    const defList = tagList.map((item) => {
      return {
        id: item.id + '',
        name: item.name,
        isDefault: true,
      }
    })
    return [...defList, ...tags]
  }, [tagList, tags])

  // 处理标签选择
  const handleTagSelect = (tagName: string, checked: boolean) => {
    if (selectedTags.length >= 5 && checked) {
      toast({
        variant: 'destructive',
        description: 'Maximum of 5 tags',
        duration: 2000,
      })
      return
    }
    setSelectedTags((prevTags) => {
      if (checked) {
        return [...prevTags, tagName]
      } else {
        return prevTags.filter((id) => id !== tagName)
      }
    })
  }

  // 添加新标签
  const handleAddTag = () => {
    if (!newTagName.trim()) return
    const newTag: Tag = {
      id: Date.now().toString(),
      name: newTagName.trim(),
      isDefault: false,
    }
    setTags([...tags, newTag])
    setNewTagName('')
  }

  // 删除标签（仅限非默认标签）
  const handleDeleteTag = (tagId: string) => {
    setTags(tags.filter((tag) => tag.id !== tagId))
  }

  // 开始编辑标签
  // const handleStartEdit = (tagId: string) => {
  //   setTags(
  //     tags.map((tag) => (tag.id === tagId ? { ...tag, isEditing: true } : tag)),
  //   )
  // }

  // 保存编辑后的标签名
  const handleSaveEdit = (tagId: string, newName: string) => {
    if (!newName.trim()) return
    setTags(
      tags.map((tag) =>
        tag.id === tagId ? { ...tag, name: newName.trim(), isEditing: false } : tag,
      ),
    )
  }

  // 取消编辑
  const handleCancelEdit = (tagId: string) => {
    setTags(
      tags.map((tag) => (tag.id === tagId ? { ...tag, isEditing: false } : tag)),
    )
  }

  const handleSubmit = async (close: () => void) => {
    console.log('uploadCallback.current:', uploadCallback.current)
    if (!uploadCallback.current && !editItem?.id) {
      return toast({
        variant: 'destructive',
        description: 'Please upload a file first',
        duration: 2000,
      })
    }
    // 验证是否选择了标签
    if (selectedTags.length === 0) {
      return toast({
        variant: 'destructive',
        description: 'Please select at least one label',
        duration: 2000,
      })
    }
    try {
      let fileInfo: { ext: string; name: string; url: string } = editItem!
      if (uploadCallback.current) {
        fileInfo = await uploadCallback.current()
      } else if (editItem) {
        fileInfo = editItem
      }

      await commonService.resourceStore({
        id: editItem?.id || '',
        ext: fileInfo.ext,
        name: fileName || fileInfo.name,
        url: fileInfo.url,
        public: isPublic === '1' ? 1 : 0,
        tags: selectedTags,
      })

      toast({
        description: 'Upload successfully',
        duration: 2000,
      })
      if (onSuccess) {
        onSuccess()
      }
      close()
    } catch (error) {
      console.error(error)
      toast({
        variant: 'destructive',
        description: 'Upload failed, please try again',
        duration: 2000,
      })
    }
  }

  const setCallbackFn = (fn: any) => {
    uploadCallback.current = fn
  }

  const handleOpenChange = (state: boolean) => {
    console.log('🚀 ~ handleOpenChange ~ state:', state)
    if (!state) {
      uploadCallback.current = null
      setTags([])
      setNewTagName('')
      setIsPublic('0')
      setFileName('')
      setSelectedTags([])
      onOpen(false)
    } else {
      onOpen(true)
    }
  }

  return (
    <CustomDialog
      className="max-w-2xl h-[440px] overflow-y-auto"
      title={editItem?.id ? 'Edit' : 'Upload'}
      trigger={children}
      open={open}
      onOpenChange={handleOpenChange}
      fnChildren={(handleCancel) => (
        <div className="space-y-10">
          <div className="flex flex-row gap-8">
            <div className="flex-1 space-y-4">
              <div className="space-y-2.5">
                <Label>Name</Label>
                <Input
                  type="text"
                  className="border-transparent border focus:border-[#A091FD] bg-white/5 placeholder:text-white/40"
                  placeholder="Please fill in the name"
                  value={fileName}
                  onChange={(e) => setFileName(e.target.value)}
                />
              </div>
              <div className="space-y-2.5">
                <Label>Whether public resources</Label>
                <RadioGroup
                  className="flex flex-row gap-8"
                  defaultValue=""
                  value={isPublic}
                  onValueChange={(val) => {
                    setIsPublic(val)
                  }}
                >
                  <Label
                    htmlFor="r1"
                    className="flex-1 flex items-center justify-center cursor-pointer space-x-2 bg-white/5 rounded-lg p-2 h-9"
                  >
                    <RadioGroupItem
                      value="1"
                      id="r1"
                      // className="border-white/40 data-[state=checked]:border-primary"
                    />
                    <span>Yes</span>
                  </Label>
                  <Label
                    htmlFor="r2"
                    className="flex-1 flex items-center justify-center cursor-pointer space-x-2 bg-white/5 rounded-lg p-2 h-9"
                  >
                    <RadioGroupItem
                      value="0"
                      id="r2"
                      // className="border-white/40 data-[state=checked]:border-primary"
                    />
                    <span>No</span>
                  </Label>
                </RadioGroup>
              </div>
              <div className="space-y-2.5">
                <Label className="flex items-center">
                  <span>File</span>
                  <span className="text-red-500 ml-1 size-2">*</span>
                </Label>
                <FileUploadButton
                  onUpload={(fileUrl, fileInfo) => {
                    const tipsName = fileInfo?.name as string
                    console.log('🚀 ~ fileInfo:', fileInfo)
                    console.log('🚀 ~ fileUrl:', fileUrl)
                    console.log('🚀 ~ FileList ~ tipsName:', tipsName)
                  }}
                  onExecUpload={(fn) => setCallbackFn(fn)}
                  accept="*"
                  maxSize={200 * 1024 * 1024}
                  trigger={({ fileInfo }) => (
                    <div className="w-full relative">
                      <Button
                        variant="outline"
                        className="w-full h-[38px] bg-white/5 border-[#A091FD] text-white rounded-xl"
                      >
                        <div className="absolute inset-0 px-4 flex items-center">
                          <div className="w-full truncate">
                            {fileInfo?.name || 'Upload'}
                          </div>
                        </div>
                      </Button>
                    </div>
                  )}
                />
              </div>
            </div>
            <div className="flex-1">
              <div className="space-y-2">
                <Label className="flex items-center">
                  <span>Label</span>
                  <span className="text-red-500 ml-1 size-2">*</span>
                </Label>
                <div className="rounded-xl p-2.5 space-y-2 bg-white/5">
                  {/* 添加新标签的输入框 */}
                  <div className="flex items-center space-x-2 mb-10">
                    <Input
                      value={newTagName}
                      onChange={(e) => setNewTagName(e.target.value)}
                      placeholder="add new label"
                      className="flex-1 h-9 border-transparent hover:border-[#A091FD] focus:border-[#A091FD] bg-white/5 placeholder:text-white/40"
                    />
                    <Button
                      variant="outline"
                      size="icon"
                      className="h-9 w-9 bg-[#A091FD]/10 border-none hover:bg-[#A091FD]/20"
                      onClick={handleAddTag}
                    >
                      <Plus className="h-4 w-4" />
                    </Button>
                  </div>

                  {/* 标签列表 */}
                  <div className="overflow-y-auto my-scrollbar max-h-32 space-y-2.5">
                    {showTagList.map((tag) => (
                      <div key={tag.id} className="flex items-center space-x-1">
                        <Checkbox
                          id={tag.id}
                          checked={selectedTags.includes(tag.name)}
                          // className="border-white data-[state=checked]:border-primary"
                          onCheckedChange={(checked) =>
                            handleTagSelect(tag.name, checked as boolean)
                          }
                        />
                        {tag.isEditing ? (
                          <div className="flex-1 flex items-center space-x-2">
                            <Input
                              defaultValue={tag.name}
                              className="h-8"
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  handleSaveEdit(tag.id, e.currentTarget.value)
                                }
                              }}
                            />
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8"
                              onClick={() => handleCancelEdit(tag.id)}
                            >
                              <X className="h-4 w-4" />
                            </Button>
                          </div>
                        ) : (
                          <div className="flex-1 flex items-center justify-between">
                            <label
                              htmlFor={tag.id}
                              className="cursor-pointer text-sm font-medium leading-none"
                            >
                              {tag.name}
                            </label>
                            {!tag.isDefault && (
                              <div className="flex items-center space-x-1">
                                {/* <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                            onClick={() => handleStartEdit(tag.id)}
                          >
                            <Pencil className="h-4 w-4" />
                          </Button> */}
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-8 w-8"
                                  onClick={() => handleDeleteTag(tag.id)}
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="w-full flex items-center justify-center">
            <Button
              className="w-72 h-11 rounded-full text-base"
              onClick={() => handleSubmit(handleCancel)}
            >
              Confirm
            </Button>
          </div>
        </div>
      )}
    />
  )
}

export default UploadDialog
